package com.mgg.user.controller.shop;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.mgg.common.enums.UserRoleEnum;
import com.mgg.common.util.ResultVOUtil;
import com.mgg.user.entity.ShopDO;
import com.mgg.common.entity.UserDO;
import com.mgg.user.enums.UserResultEnum;
import com.mgg.user.service.BaseUserService;
import com.mgg.user.service.shop.ShopService;
import com.mgg.user.service.user.UserService;
import com.mgg.user.vo.ManagerAchievementVO;
import com.mgg.user.vo.RecdUserVO;
import com.mgg.user.vo.UserInfoVO;
import com.mgg.user.vo.UserSimpleVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/shop")
public class ShopController {

	@Autowired
	private UserService userService;

    @Autowired
    private ShopService shopService;

	@Autowired
    private BaseUserService baseUserService;

	/**
	 * 根据shopCode获取店铺信息
	 * @param shopCode
	 * @return
	 * @throws Exception
	 */
	@GetMapping(value="/info/{code}")
	public Object findShopByCode(@PathVariable("code") String shopCode) {
        UserInfoVO userInfoVO = userService.getUserInfoByShopCode(shopCode);
        return ResultVOUtil.success(userInfoVO);
	}
	
	/**
	 * 我的会员
	 * @param userId
	 * @return
	 * @throws Exception
	 */
	@GetMapping(value="/statistics")
	public Object getTutorShopStatistics(@RequestHeader("user_id") String userId, @RequestParam String shopCode) {
		if (!isAbleToAccess(userId,shopCode)) {
			return ResultVOUtil.error(UserResultEnum.ACCESS_DENIED);
		}

        UserDO user = baseUserService.getUserByShopCode(shopCode);
		Map<String,Object> result = shopService.getTutorStatistics(user.getUserId(),shopCode);

		Map<String,Object> shopkeeper = new HashMap<>();
		shopkeeper.put("username", user.getUsername());
		shopkeeper.put("headImg", user.getHeadImg());
		shopkeeper.put("addtime", user.getAddtime());
        ShopDO shop = baseUserService.getShopByUserId(user.getUserId());
		shopkeeper.put("shop", shop);
		if (userId.equals(user.getUserId())) {
			shopkeeper.put("isSelf", "true");
		} else {
			shopkeeper.put("isSelf", "false");
		}
		result.put("shopkeeper", shopkeeper);
		return ResultVOUtil.success(result);
	}

	/**
	 * 获取会员列表
	 * @param userId
	 * @return
	 * @throws Exception
	 */
	@GetMapping(value="/member/list")
	public Object members(@RequestHeader("user_id") String userId, @RequestParam String shopCode, 
			@PageableDefault(page = 1, size = 10) Pageable page) throws Exception {
		if (!isAbleToAccess(userId,shopCode)) {
			return ResultVOUtil.error(UserResultEnum.ACCESS_DENIED);
		}
        UserDO user = baseUserService.getUserByShopCode(shopCode);
		List<UserSimpleVO> users = shopService.listMember(user.getUserId(), page);
		return ResultVOUtil.success(users);
	}
	
	/**
	 * 我的推荐店主
	 * @param userId
	 * @return
	 * @throws Exception
	 */
	@GetMapping(value="/statistics/recdShopkeeper")
	public Object getRecdShopkeeper(@RequestHeader("user_id") String userId) throws Exception {
		Map<String,Object> result = new HashMap<>();
		UserDO user = baseUserService.getUserByUserId(userId);
        String shopCode = user.getShopCode();
		//累计销售
		result.putAll(shopService.getShopSalesCount(shopCode,user.getRoleCode()));
		//推荐店主统计（直接，间接）
		result.put("recdNum", shopService.countRecdTutorNum(shopCode));
		result.put("direct_recdNum", shopService.countDirectRecdTutorNum(shopCode));
		return ResultVOUtil.success(result);
	}
	
	/**
	 * 我的推荐店主列表
	 * @param userId
	 * @return
	 * @throws Exception
	 */
	@GetMapping(value="/statistics/recdShopkeeper/list")
	public Object getRecdShopkeeperList(@RequestHeader("user_id") String userId,
				@PageableDefault(page = 1, size = 20) Pageable page) throws Exception {
        UserDO user = baseUserService.getUserByUserId(userId);
        String shopCode = user.getShopCode();
		List<RecdUserVO> users = shopService.listRecdShopkeeper(shopCode, page);
		return ResultVOUtil.success(users);
	}

	/** v2 api **/
	
	/**
	 * 社群培训
	 * @param userId
	 * @return
	 * @throws Exception
	 */
	@GetMapping(value="/community")
	public Object getCommunityInfo(@RequestHeader("user_id") String userId, @RequestParam String shopCode) throws Exception {
		if (!isAbleToAccess(userId,shopCode)) {
			return ResultVOUtil.error(UserResultEnum.ACCESS_DENIED);
		}
        UserDO user = baseUserService.getUserByShopCode(shopCode);
		Map<String,Object> result = shopService.getCommunityInfo(user.getUserId(), user.getRoleCode());
		return ResultVOUtil.success(result);
	}
	
	/**
	 * 社群培训
	 * @param userId
	 * @return
	 * @throws Exception
	 */
	@GetMapping(value="/community/members")
	public Object getCommunityMemberList(@RequestHeader("user_id") String userId, @RequestParam String shopCode,
			@RequestParam String roleCode, @PageableDefault(page = 1, size = 20) Pageable page) throws Exception {
		if (!isAbleToAccess(userId,shopCode)) {
			return ResultVOUtil.error(UserResultEnum.ACCESS_DENIED);
		}
		Map<String,Object> result = new HashMap<>();
        UserDO user = baseUserService.getUserByShopCode(shopCode);
		if (UserRoleEnum.TUTOR.getCode().equals(roleCode)) {	
			return ResultVOUtil.success(shopService.listCommunityDirectTutor(user.getUserId(), shopCode, page));
		} else if (UserRoleEnum.MANAGER.getCode().equals(roleCode)) {
			return ResultVOUtil.success(shopService.listCommunityDirectManage(user.getUserId(), shopCode, page));
		}
		return ResultVOUtil.success(result);
	}
	
	/**
	 * 社群业绩
	 * @param userId
	 * @return
	 * @throws Exception
	 */
	@GetMapping(value="/community/achievement/count")
	public Object getCommunityAchievement(@RequestHeader("user_id") String userId, @RequestParam String shopCode) throws Exception {
		if (!isAbleToAccess(userId,shopCode)) {
			return ResultVOUtil.error(UserResultEnum.ACCESS_DENIED);
		}
        UserDO user = baseUserService.getUserByShopCode(shopCode);
		Map<String,Object> result = shopService.getCommunityAchievement(user.getUserId(), shopCode);	
		return ResultVOUtil.success(result);
	}
	
	
	/**
	 * 社群业绩明细列表
	 * @param userId
	 * @return
	 * @throws Exception
	 */
	@GetMapping(value="/community/achievement/list")
	public Object getCommunityAchievementList(@RequestHeader("user_id") String userId, @RequestParam String shopCode, @RequestParam String month,
			@PageableDefault(page = 1, size = 20) Pageable page) throws Exception {
		if (!isAbleToAccess(userId,shopCode)) {
			return ResultVOUtil.error(UserResultEnum.ACCESS_DENIED);
		}
		UserDO user = baseUserService.getUserByShopCode(shopCode);
        List<ManagerAchievementVO> list = shopService.listCommunityAchievement(user.getUserId(), shopCode, month, page);
		return ResultVOUtil.success(list);
	}

	/**
	 * 是否允许访问
	 * @param userId
	 * @param shopCode
	 * @return
	 * @throws Exception
	 */
	private boolean isAbleToAccess(String userId, String shopCode) {
		UserDO user = baseUserService.getUserByUserId(userId);
		if (UserRoleEnum.VIP.getCode().equals(user.getRoleCode())) {
			return false;
		} else if (shopCode.equals(user.getShopCode())) {
			return true;
		} else {			
			Map<String,String> map = new HashMap<>();
			map.put("userId", userId);
			map.put("shopCode", shopCode);
			return shopService.isMyLowerShop(map);
		}
	}
	
	/**
	 * 店铺访问
	 * @param shopCode
	 * @return
	 * @throws Exception
	 */
	@GetMapping(value="/{code}/visit")
	public Object visitShop(@PathVariable("code") String shopCode) throws Exception {
		shopService.visitShop(shopCode);
		return ResultVOUtil.success();
	}
	
}
